package com.leetcodehot.problems;

import java.util.List;

public class problems1239 {
    private int n;
    private int res;
    private int length;
    private int[] count;

    public int maxLength(List<String> arr) {
        n = arr.size();
        res = 0;
        length = 0;
        count = new int[26];
        dfs(arr, 0);
        return res;
    }

    private void dfs(List<String> arr, int i) {
        if (i == n) {
            res = Math.max(res, length);
            return;
        }
        //不选当前的
        dfs(arr, i + 1);

        //选
        if (countEnable(arr, i)) {
            for (char c : arr.get(i).toCharArray()) {
                count[c - 'a']++;
            }
            length += arr.get(i).length();
            dfs(arr, i + 1);
            length -= arr.get(i).length();
            for (char c : arr.get(i).toCharArray()) {
                count[c - 'a']--;
            }
        }
    }

    private boolean countEnable(List<String> arr, int i) {
        int[] temp = new int[26];
        for (char c : arr.get(i).toCharArray()) {
            if (count[c - 'a'] == 1 || temp[c - 'a'] > 0) {
                return false;
            }
            temp[c - 'a']++;
        }
        return true;
    }
}
